package com.jukte.recipe;

import java.util.ArrayList;
import java.util.List;
import com.ewhat.recipes.R;
import com.jukte.recipe.db.DataBaseManager;
import com.jukte.recipe.models.Category;
import com.jukte.recipe.models.SubCategory;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class RecipeTabFragment extends Fragment {
	
	private LayoutInflater inflater;
	private TableLayout menu_table=null;

	private List<Category> categories;
	private Context con;
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		menu_table=(TableLayout)getActivity().findViewById(R.id.reciepe_category_table);
		new GetCategoryDataTask().execute();
	}

	View.OnClickListener getOnClickCategoryItem(final View categoryView)  {
	    return new View.OnClickListener() {
	        public void onClick(View v) {
	         new MenuButtonClickTask((Category)categoryView.getTag()).execute();
	        }
	    };
	}
	
	
	private View getMenuItemView(Category cat) {
		View v=inflater.inflate(R.layout.item_recipe_menu, null);
		v.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
		TextView title=(TextView)v.findViewById(R.id.menu_text);
		title.setText(cat.getCategoryName());
		ImageView img=(ImageView)v.findViewById(R.id.menu_image);
		
		Bitmap bmp = BitmapFactory.decodeFile(getActivity().getFilesDir().getPath()+"/raw/"+cat.getImgPath());
		int resId = getActivity().getResources().getIdentifier("quinoa_menuicon","raw", getActivity().getPackageName());
		
		if(null != bmp){
			img.setImageBitmap(bmp);
		}else{
			img.setImageResource(resId);
		}
		
		v.setTag(cat);
		v.setOnClickListener(getOnClickCategoryItem(v));
		return v;
	}
	
	private View getFavMenuItem()
	{
		View v=inflater.inflate(R.layout.item_recipe_menu, null);
		v.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
		TextView title=(TextView)v.findViewById(R.id.menu_text);
		title.setText("Favorites");
		ImageView img=(ImageView)v.findViewById(R.id.menu_image);
		int resId = getActivity().getResources().getIdentifier("favorites_menu_icon","raw", getActivity().getPackageName());
		img.setImageResource(resId);
		v.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(getActivity(), FavRecipeListActivity.class);
				
				startActivity(intent);
			}
		});
		return v;
	}
	
	private TableRow getATableRow()
	{
		TableRow tableRow=new TableRow(getActivity());
        tableRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        tableRow.setPadding(0, 0, 0, 0);
        return tableRow;
	}

	public void updateMenuTable() {
		menu_table.removeAllViews();
		boolean flag = true;
		if (categories.size() > 0) {
			for (int i = 0; i < categories.size();) {
				TableRow tableRow=getATableRow();
				int j = i;
				while (j < i + 2) {
					if (j == categories.size()) {
						tableRow.addView(getFavMenuItem());
						flag = false;
						break;
					}

					tableRow.addView(getMenuItemView(categories.get(j)));
					j++;
				}
				menu_table.addView(tableRow);
				i = j;
			}
			if(flag)
			{
			TableRow tr=getATableRow();
			tr.addView(getFavMenuItem());
			menu_table.addView(tr);
			}
		}
	}
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		con=getActivity();
		
	}

	private void loadCategoryData() {
		// TODO Auto-generated method stub
		categories=DataBaseManager.getInstance().getAllcategories();
		DataBaseManager.getInstance().closeDb();
		
	}

	/* (non-Javadoc)
	 * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (container == null) {
            // We have different layouts, and in one of them this
            // fragment's containing frame doesn't exist.  The fragment
            // may still be created from its saved state, but there is
            // no reason to try to create its view hierarchy because it
            // won't be displayed.  Note this is not needed -- we could
            // just run the code below, where we would create and return
            // the view hierarchy; it would just never be used.
            return null;
        }
		View view=inflater.inflate(R.layout.frag_recipe, container,false);
        //return super.onCreateView(inflater, container, savedInstanceState);
		return view;
		//return (LinearLayout)inflater.inflate(R.layout.recipe_frag_layout, container, false);
	}
	
	public class GetCategoryDataTask extends AsyncTask<Void, Void, Void> 
    {
        public ProgressDialog progDialog=null;
        
        
        
        protected void onPreExecute() 
        {
            progDialog=ProgressDialog.show(con, "", "Loading...",true);
        }
        @Override
        protected Void doInBackground(Void... params) 
        {
           loadCategoryData();
           return null;
        }    
            
        


		


		protected void onPostExecute(Void result) 
        {
            if(progDialog.isShowing())
            {
                progDialog.dismiss();
            }
            updateMenuTable();
        }
    }

	public class MenuButtonClickTask extends AsyncTask<Void, Void, Void> 
    {
        public ProgressDialog progDialog=null;
        private Category selectedCat;
        private List<SubCategory> subCategories;
        public MenuButtonClickTask(Category cat) {
            super();
           // selectedId=id;
            selectedCat=cat;
            subCategories=new ArrayList<SubCategory>();
        }
        
        
        
        protected void onPreExecute() 
        {
           // progDialog=ProgressDialog.show(con, "", "Loading...",true);
        }
        @Override
        protected Void doInBackground(Void... params) 
        {
        	getSubCategories();
        	return null;
        }    
            
        

        private void getSubCategories()
        {
        	subCategories=DataBaseManager.getInstance().getAllSubCategoriesByCategoryId(selectedCat.getId());
    		DataBaseManager.getInstance().closeDb();
        }
		


		protected void onPostExecute(Void result) 
        {
            /*if(progDialog.isShowing())
            {
                progDialog.dismiss();
            }*/
            goToIntentdedScreen();
        }



		private void goToIntentdedScreen() {
			// TODO Auto-generated method stub
			if(selectedCat.getId() == 2 || selectedCat.getId() == 3){
				Intent intent=new Intent(getActivity(), RecipeListActivity.class);
				intent.putExtra("CATEGORY_ID", selectedCat.getId());
				intent.putExtra("TITLE",selectedCat.getCategoryName()+" Menu");
				startActivity(intent);
			}else if(subCategories.size()>1){
				Intent intent=new Intent(getActivity(), SubCategoryActivity.class);
				intent.putExtra("CATEGORY_ID", selectedCat.getId());
				intent.putExtra("CATEGORY_NAME", selectedCat.getCategoryName());
				intent.putExtra("TITLE", selectedCat.getCategoryName()+" Menu");
				startActivity(intent);
			}
			else if(subCategories.size()==1)
			{
				Intent intent=new Intent(getActivity(), RecipeListActivity.class);
				intent.putExtra("SUB_CAT_ID",subCategories.get(0).getId());
				intent.putExtra("TITLE",subCategories.get(0).getName()+" Menu");
				startActivity(intent);
			}
		}
    }
	
}
